#include "OssManager.h"
#include "LoadConfig.h"

//初始化为null
unique_ptr<OssClient> OssManager::m_client = nullptr;

void OssManager::init(){
    /* 初始化网络等资源。*/
    InitializeSdk();

    auto config = LoadConfig::loadConfig();
    // 1. 初始化OSS账号信息
    std::string endpoint = config["ENDPOINT"];
    std::string accessKeyId = config["ACCESSKEYID"];
    std::string accessKeySercret = config["ACCESSKEYSECRET"];

    ClientConfiguration conf;
    m_client = std::make_unique<OssClient>(endpoint ,accessKeyId, accessKeySercret, conf);

    std::string region = config["REGION"];
    m_client->SetRegion(region);
}

void OssManager::shutdown(){
    /* 释放网络等资源。*/
    ShutdownSdk();
}

int OssManager::upload(const string& fileName,const string &fileContent){
    if(!m_client){
        std::cerr << "OSS client is not initialized!" << std::endl;
        return -1;
    }
    
    // 2. 上传文件
    auto config = LoadConfig::loadConfig();
    std::string bucketName = config["BUCKET_NAME"];
    std::string objectName = config["OBJECT_PATH"] + fileName;

    std::shared_ptr<std::iostream> stream = std::make_shared<std::stringstream>(std::move(fileContent));

    PutObjectRequest request { bucketName, objectName, stream };

    auto outcome = m_client->PutObject(request);

    if (!outcome.isSuccess()) {
        /* 异常处理。*/
        std::cout << "PutObject fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }
    return 0;
}